<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-[32rpx] box-border">
    <!-- <backView /> -->
    
    <!-- 认证提示卡片 -->
    <view class="auth-notice-card mt-[100rpx] py-8" v-if="noData">
      <!-- 图标区域 -->
      <view class="icon-container mb-[40rpx]">
        <IconFont name="dongdong" size="60" color="#3b82f6"></IconFont>
      </view>
      
      <!-- 标题 -->
      <view class="title">实名认证提醒</view>
      
      <!-- 内容 -->
      <view class="content">
        <text class="main-text">被监护人未实名认证</text>
        <text class="sub-text">不能获取信息，请先完成实名认证</text>
      </view>
      
      <!-- 操作按钮 -->
      <!-- <view class="action-buttons">
        <button class="primary-btn" @click="handleAuth">
          <IconFont name="icon-check" class="btn-icon" />
          <text>立即认证</text>
        </button>
        <button class="secondary-btn" @click="handleContact">
          <IconFont name="icon-phone" class="btn-icon" />
          <text>联系客服</text>
        </button>
      </view> -->
      
      <!-- 底部提示 -->
      <view class="footer-tip">
        <!-- <IconFont name="icon-info" class="tip-icon" /> -->
        <text>认证后可享受完整的健康评估服务</text>
      </view>
    </view>
    
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { request } from '@/service/request'
import { localStg } from "../utils";
import { useMedicalRecordStore } from '@/store/modules'
const noData = ref(false)
Taro.showLoading({
  title: "加载中...",
});

// 获取 store 实例
const medicalRecordStore = useMedicalRecordStore()

// 功能预览数据
const previewItems = ref([
  { name: '健康评估', icon: 'icon-assessment' },
  { name: '护理评估', icon: 'icon-file' },
  { name: '专科评估', icon: 'icon-home' },
  { name: '治疗计划', icon: 'icon-history' }
]);

// 处理认证按钮点击
const handleAuth = () => {
  Taro.showToast({
    title: "跳转到认证页面",
    icon: "none",
  });
  // 这里可以添加跳转到认证页面的逻辑
  // Taro.navigateTo({
  //   url: "/pages/auth/index"
  // });
};

// 处理联系客服按钮点击
const handleContact = () => {
  Taro.showModal({
    title: "联系客服",
    content: "客服电话：400-123-4567\n工作时间：9:00-18:00",
    showCancel: true,
    cancelText: "取消",
    confirmText: "拨打电话",
    success: (res) => {
      if (res.confirm) {
        // 这里可以添加拨打电话的逻辑
        Taro.showToast({
          title: "正在拨打电话...",
          icon: "none",
        });
      }
    }
  });
};

onMounted(async () => {
  console.log("onMounted");
  Taro.showLoading({
    title: "加载中...",
  });
  const res = await loadInfo();
  if(!res){
    setTimeout(() => {
      loadInfo();
      Taro.hideLoading();
    }, 1200);
  }else{
    Taro.hideLoading();
  }
  
});

async function loadInfo() {
  const obj = localStg.get("demographicInfo");
  if(!obj || !obj.idNumber){
    // Taro.showToast({
    //   title: "未获取到用户信息",
    //   icon: "none",
    // });
    noData.value = true
    return false
  }
  // https://anfine.huasun-healthcare.com/api/health_records/past_medical/pastMedicalInfo/queryById?_t=1758474714444&id=1967390181354524674
  request.get<any>(`/health_records/past_medical/pastMedicalInfo/list`, {
    idNumber: obj.idNumber,
  }, {
    useErrMsg: true,
  }).then(async (res:any) => {
    console.log("res===", res);
    const item = res.success?.records?.pop();
    if (item) {
      await loadRecordData(item.id);
      Taro.redirectTo({
        url: "/pages/medical-record/sub-form?type=allCareAssessment",
      });
    }
    else{
      noData.value = true
      Taro.hideLoading();
    }
  });
  return true
}


/**
 * 加载记录数据
 */
 async function loadRecordData(id: string) {
  try {
    console.log('开始加载记录数据====ID:', id)
    
    // 请求记录详情
    const { success } = await request.get<any>(`/health_records/past_medical/pastMedicalInfo/queryById`, {
      id: id
    }, {
      useErrMsg: true
    })
    
    if (success) {
      console.log('加载的记录数据:', success)
      
      // 如果有 note 数据，尝试解析并加载到 store
      if (success.note) {
        try {
          const noteData = JSON.parse(success.note)
          console.log('解析的 note 数据:', noteData)
          
          // 转换为扁平化的表单数据
          const formData = medicalRecordStore.noteToFormData(noteData)
          
          // 设置基本信息
          formData.id = success.id || ''
          formData.name = success.name || ''
          formData.idNumber = success.idNumber || ''
          formData.recordid = success.recordid || ''
          
          // 初始化表单数据
          medicalRecordStore.initializeFormData(formData)
        } catch (parseError) {
          console.error('解析 note 数据失败:', parseError)
          // 如果解析失败，使用默认数据并填充基本信息
          medicalRecordStore.initializeFormData()
        }
      } else {
        // 如果没有 note 数据，使用默认数据
        medicalRecordStore.initializeFormData()
      }
      
      // 更新基本信息到 store
      medicalRecordStore.updateField('id', success.id || '')
      medicalRecordStore.updateField('name', success.name || '')
      medicalRecordStore.updateField('idNumber', success.idNumber || '')
      medicalRecordStore.updateField('recordid', success.recordid || '')
      
      // 更新其他字段到 store（如果 note 中没有的话）
      if (success.seeDate) {
        medicalRecordStore.updateField('visitTime', success.seeDate)
      }
      if (success.chiefComplaint) {
        medicalRecordStore.updateField('chiefComplaint', success.chiefComplaint)
      }
      if (success.diagnosisResult) {
        medicalRecordStore.updateField('diagnosisResult', success.diagnosisResult)
      }
      if (success.diagnosisBasis) {
        medicalRecordStore.updateField('diagnosisBasis', success.diagnosisBasis)
      }
      if (success.hospital) {
        medicalRecordStore.updateField('hospital', success.hospital)
      }
      if (success.department) {
        medicalRecordStore.updateField('department', success.department)
      }
      if (success.specialistAssessment) {
        medicalRecordStore.updateField('specialistAssessment', success.specialistAssessment)
      }
      if (success.surgeryName) {
        medicalRecordStore.updateField('surgeryName', success.surgeryName)
      }
      if (success.surgeryTime) {
        medicalRecordStore.updateField('surgeryTime', success.surgeryTime)
      }
      if (success.surgeryHospital) {
        medicalRecordStore.updateField('surgeryHospital', success.surgeryHospital)
      }
      if (success.medicationAllergy) {
        medicalRecordStore.updateField('medicationAllergy', success.medicationAllergy)
      }
      if (success.foodAllergy) {
        medicalRecordStore.updateField('foodAllergy', success.foodAllergy)
      }
      if (success.otherAllergy) {
        medicalRecordStore.updateField('otherAllergy', success.otherAllergy)
      }
      if (success.familyDiseaseHistory) {
        medicalRecordStore.updateField('familyHistory', success.familyDiseaseHistory)
      }
      if (success.physicalExamination) {
        medicalRecordStore.updateField('physicalExamination', success.physicalExamination)
      }
      if (success.organExamination) {
        medicalRecordStore.updateField('organExamination', success.organExamination)
      }
      if (success.auxiliaryExamination) {
        medicalRecordStore.updateField('auxiliaryExamination', success.auxiliaryExamination)
      }
      if (success.prescription) {
        medicalRecordStore.updateField('prescription', success.prescription)
      }
      if (success.disposition) {
        medicalRecordStore.updateField('disposition', success.disposition)
      }
      if (success.healthEducation) {
        medicalRecordStore.updateField('healthEducation', success.healthEducation)
      }
    }
  } catch (error) {
    console.error('加载记录数据失败:', error)
    Taro.showToast({ title: '加载数据失败', icon: 'error' })
  }
}

</script>

<style lang="scss" scoped>
/* 认证提示卡片 */
.auth-notice-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  border-radius: 24rpx;
  padding: 48rpx 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
  border: 2rpx solid rgba(59, 130, 246, 0.1);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6rpx;
    background: linear-gradient(90deg, #3b82f6, #8b5cf6, #06b6d4);
  }
}

.icon-container {
  display: flex;
  justify-content: center;
  margin-bottom: 24rpx;
}

.auth-icon {
  font-size: 80rpx;
  color: #3b82f6;
  background: linear-gradient(135deg, #dbeafe 0%, #e0e7ff 100%);
  padding: 24rpx;
  border-radius: 50%;
  box-shadow: 0 4rpx 16rpx rgba(59, 130, 246, 0.2);
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #1e293b;
  text-align: center;
  margin-bottom: 16rpx;
}

.content {
  text-align: center;
  margin-bottom: 32rpx;
}

.main-text {
  display: block;
  font-size: 28rpx;
  color: #ef4444;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.sub-text {
  display: block;
  font-size: 24rpx;
  color: #64748b;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.primary-btn {
  flex: 1;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border: none;
  border-radius: 16rpx;
  padding: 20rpx 24rpx;
  font-size: 28rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  box-shadow: 0 4rpx 16rpx rgba(59, 130, 246, 0.3);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 8rpx rgba(59, 130, 246, 0.3);
  }
}

.secondary-btn {
  flex: 1;
  background: white;
  color: #3b82f6;
  border: 2rpx solid #e2e8f0;
  border-radius: 16rpx;
  padding: 20rpx 24rpx;
  font-size: 28rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  transition: all 0.3s ease;

  &:active {
    background: #f1f5f9;
    border-color: #3b82f6;
  }
}

.btn-icon {
  font-size: 24rpx;
}

.footer-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 16rpx;
  background: rgba(59, 130, 246, 0.05);
  border-radius: 12rpx;
  border: 1rpx solid rgba(59, 130, 246, 0.1);
}

.tip-icon {
  font-size: 20rpx;
  color: #3b82f6;
}

.footer-tip text {
  font-size: 22rpx;
  color: #64748b;
}

/* 功能预览卡片 */
.preview-card {
  background: white;
  border-radius: 20rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  border: 1rpx solid #e2e8f0;
}

.preview-title {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #f1f5f9;
}

.preview-icon {
  font-size: 28rpx;
  color: #8b5cf6;
}

.preview-title text {
  font-size: 30rpx;
  font-weight: 600;
  color: #1e293b;
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx;
}

.preview-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24rpx 16rpx;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 16rpx;
  border: 1rpx solid #e2e8f0;
  transition: all 0.3s ease;

  &:active {
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }
}

.preview-item-icon {
  font-size: 32rpx;
  color: #6366f1;
  margin-bottom: 8rpx;
}

.preview-item-text {
  font-size: 24rpx;
  color: #475569;
  font-weight: 500;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .action-buttons {
    flex-direction: column;
  }
  
  .preview-grid {
    grid-template-columns: 1fr;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.auth-notice-card,
.preview-card {
  animation: fadeInUp 0.6s ease-out;
}

.preview-card {
  animation-delay: 0.2s;
}
</style>
